﻿using DoNetDrive.Core.Packet;
using DotNetty.Buffers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _8280WEBSocket.Command.Json
{
    public class JsonPacketDecompile : INPacketDecompile
    {
        public string mCacheJson { get; set; }
        public bool Decompile(IByteBuffer buf, List<INPacket> retPacketList)
        {
            var vbCr = "\r";
            var vbLf = "\n";
            var sJson = buf.ReadString(buf.ReadableBytes, JsonPacket.JsonEncoding);
            sJson = sJson.Trim();
            if (sJson.Contains(Environment.NewLine))
                sJson = sJson.Replace(Environment.NewLine, string.Empty);
            if (sJson.Contains(vbCr))
                sJson = sJson.Replace(vbCr, string.Empty);
            if (sJson.Contains(vbLf))
                sJson = sJson.Replace(vbLf, string.Empty);
            if (sJson.StartsWith("{") && sJson.EndsWith("}"))
            {
                retPacketList.Add(new JsonPacket(sJson));
                mCacheJson = string.Empty;
                return true;
            }
            else if (string.IsNullOrEmpty(mCacheJson))
            {
                if (sJson.StartsWith("{"))
                    mCacheJson = sJson; // 先缓存
                else
                    return false;// 啥也不干，丢弃消息
            }
            else
            {
                mCacheJson += sJson;

                if (mCacheJson.EndsWith("}"))
                {
                    retPacketList.Add(new JsonPacket(sJson));
                    mCacheJson = string.Empty;
                    return true;
                }
            }
            return false;
        }

        public void Dispose()
        {
            
        }
    }
}
